package com.jinsi.common;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (request.getServletPath().equals("/register.html") || request.getServletPath().equals( "/register")){
            return true;
        }else if (session.getAttribute("user") != null) {
            return true;
        }
        else {
            response.sendRedirect("/");
            return false;
        }

    }

    public List<String> getUrls() {

        /**
         * 用于存储排除拦截的url  （登录/login.html, /css,/js,/img）
         */

        List<String> urls = new ArrayList<>();
        urls.add("/");     // 默认页面请求
        urls.add("/login");     // 登录页面请求
        urls.add("/register");  //注册请求
        urls.add("/getLoginByAccount");   //  登录请求
        urls.add("/getMSM");        //验证码
        urls.add("/getLoginByPhone");   //手机号
        urls.add("/getRegister");

        // 静态资源
        urls.add("/image/**");
        urls.add("/js/**");
        urls.add("/css/**");
        urls.add("/layui/**");
        urls.add("/layui-修改/**");

        return urls;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("我被拦截了。。。postHandle。。。LoginInterceptor");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//        System.out.println("我被拦截了。。。afterCompletion。。。LoginInterceptor");
    }





}
